import pymysql

def dbIsExistCreateAndConnect(user, passwd, dbName, charset):
    # 尝试连接到默认数据库（通常是 'mysql' 或 'information_schema'）
    conn = pymysql.connect(host="127.0.0.1", port=3306, user=user, passwd=passwd, charset=charset)
    try:
        with conn.cursor() as cursor:
            cursor.execute("SHOW DATABASES")
            result = cursor.fetchall()
            for db in result:

                if db[0] == dbName:
                    # 数据库存在，返回连接到该数据库的新连接
                    new_conn = pymysql.connect(host="127.0.0.1", port=3306, user=user, passwd=passwd, db=dbName, charset=charset)
                    conn.close()  # 关闭原始连接
                    return new_conn
        # 数据库不存在，尝试创建并连接
        conn.close()  # 在这里关闭原始连接是安全的，因为我们还没有创建新连接
        with pymysql.connect(host="127.0.0.1", port=3306, user=user, passwd=passwd, charset=charset) as temp_conn:
            with temp_conn.cursor() as cursor:
                cursor.execute(f"CREATE DATABASE {dbName}")
        # 创建后，返回连接到新数据库的连接
        return pymysql.connect(host="127.0.0.1", port=3306, user=user, passwd=passwd, db=dbName, charset=charset)
    except pymysql.MySQLError as e:
        # 处理任何 MySQL 错误
        print(f"Error: {e}")
        conn.close()  # 确保在发生错误时关闭连接
        return None
